import React, { useEffect, useState } from "react";
import style from "./style.module.scss";
import { LazyImage, MyHeader, MypatientCieclefooter, NavTitle, WDList } from "../../components";
import { useBoolean, useRequest, useSetState } from "ahooks";
import { Swiper, List } from "react-vant";
import { getTimeFormatText } from "../../utils/formatTime";
import knowUrl1 from "../../assets/images/image/hdpi/common_disease.png";
import knowUrl2 from "../../assets/images/image/hdpi/common_drugs.png";
import health from "../../assets/images/image/xxhdpi/health_assessment.png";
import { NavLink, useNavigate } from "react-router-dom";
import {
  getBanners,
  getInformation,
  getInformationListById,
  getKnowledgeBase,
} from "../../api/home";
// 轮播图类型
interface BannerRawState {
  imageUrl: string;
  jumpUrl: string;
  rank: number;
  title: string;
}

// 问诊咨询类型
interface KnowledgeBaseRawState {
  departmentName: string;
  id: number;
  pic: string;
  rank: number;
}

// 健康咨询标题类型
interface InfoRawState {
  id: number;
  name: string;
  sort: number;
}

// 健康咨询请求列表类型
interface InfoListRawState {
  id: number;
  plateId: number;
  releaseTime: number;
  source: string;
  thumbnail: string[];
  title: string;
}

const Index: React.FC = () => {
  const navigate = useNavigate();
  // 轮播请求hooks
  const { data: bannerData = [] } = useRequest<BannerRawState[], []>(
    async () => {
      const resp = await getBanners();
      return resp.result;
    }
  );
  // 问诊咨询请求hooks
  const { data: knowledgeBaseData = [] } = useRequest<
    KnowledgeBaseRawState[],
    []
  >(async () => {
    const resp = await getKnowledgeBase();
    return resp.result;
  });

  // 健康咨询标题请求hooks
  const { data: infoData = [] } = useRequest<InfoRawState[], []>(async () => {
    const resp = await getInformation();
    return resp.result;
  });

  // 健康咨询列表参数
  const [infoListParams, setInfoListParams] = useSetState({
    plateId: 1,
    count: 5,
    page: 1,
  });

  // 健康咨询列表请求hooks
  const [infoListData, setInfoListData] = useState<InfoListRawState[]>([]);
  // 是否加载完毕
  const [finish, { setTrue, setFalse }] = useBoolean(false);
  // 请求合并数据
  const mergeInfoListData = async () => {
    const resp = await getInformationListById(infoListParams);
    // 是否存在更多数据
    if (resp.result.length > 0) {
      // 数据二次处理
      resp.result.forEach((v) => {
        v.thumbnail = v.thumbnail.split(";");
      });
      // 请求第一页
      if (infoListParams.page === 1) {
        // 数据不合并
        setInfoListData(resp.result);
      } else {
        // 请求非第一页， 请求合并
        setInfoListData([...infoListData, ...resp.result]);
      }
      // 下一次请求页码 + 1
      setInfoListParams({
        page: infoListParams.page + 1,
      });
    } else {
      // 请求完成 没有更多数据
      setTrue();
    }
  };

  // 副作用 id 改变
  useEffect(() => {
    setFalse();
    mergeInfoListData();
  }, [infoListParams.plateId]);

  return (
    <div className={style["home"]}>
      <MyHeader showSearch={true}></MyHeader>
      {bannerData.length > 0 && (
        <Swiper vertical={true} className={style.banner}>
          {bannerData.map((v, i) => {
            return (
              <Swiper.Item key={i}>
                <img src={v.imageUrl} alt="" className={style.banner} />
              </Swiper.Item>
            );
          })}
        </Swiper>
      )}

      <NavTitle title="知识宝典"></NavTitle>
      <div className={style["know-1"]}>
        <div className={style["know-item"]}>
          <NavLink to="/home/knowledgebase?code=1">
            <p>常见病症</p>
            <div className={style["img-container"]}>
              <img src={knowUrl1} alt="" />
            </div>
          </NavLink>
        </div>
        <div className={style["know-item"]}>
          <NavLink to="/home/knowledgebase?code=2">
            <p>常用药品</p>
            <div className={style["img-container"]}>
              <img src={knowUrl2} alt="" />
            </div>
          </NavLink>
        </div>
      </div>
      <NavTitle title="问诊咨询"></NavTitle>
      <div className={style.know}>
        {knowledgeBaseData.map((v, i) => {
          return (
            <div
              className={style["know-item"]}
              key={i}
              onClick={() =>
                navigate(`/home/knowledgebase?code=1&left=${v.id}`)
              }
            >
              <img src={v.pic} alt="" className={style.img} />
              <span>{v.departmentName}</span>
            </div>
          );
        })}
      </div>
      <NavTitle title="健康评测"></NavTitle>
      <img src={health} alt="" width={"100%"} onClick={() => navigate('/consultation/doctor/list')}/>
      <NavTitle title="健康咨询"></NavTitle>
      <div className={style["info"]}>
        <div className={style["title"]}>
          {infoData.map((v) => {
            return (
              <span
                onClick={() => {
                  setInfoListParams({ plateId: v.id, page: 1 });
                }}
                key={v.id}
                className={
                  v.id === infoListParams.plateId ? style["active"] : ""
                }
              >
                {v.name}
              </span>
            );
          })}
        </div>
        <WDList
          finished={finish}
          onLoad={mergeInfoListData}
          finishedText="没有更多数据了"
        >
          <div className={style["content"]}>
            {infoListData.map((v) => {
              if (v.thumbnail.length === 1) {
                return (
                  // <NavLink to={`/home/information/${v.id}`} key={v.id}>
                  <dl
                    key={v.id}
                    className={style["one"]}
                    onClick={() => navigate(`/home/information/${v.id}`)}
                  >
                    <dt>
                      <LazyImage src={v.thumbnail[0]} alt="" />
                    </dt>
                    <dd>
                      <h3>{v.title}</h3>
                      <p>
                        <span>{v.source}</span>
                        <span>
                          {getTimeFormatText(new Date(v.releaseTime))}
                        </span>
                      </p>
                    </dd>
                  </dl>
                );
              } else if (v.thumbnail.length === 3) {
                return (
                  <dl
                    key={v.id}
                    className={style["three"]}
                    onClick={() => navigate(`/home/information/${v.id}`)}
                  >
                    <dd>
                      <h3>{v.title}</h3>
                    </dd>
                    <dt>
                      {v.thumbnail.map((v, i) => {
                        return <LazyImage key={i} src={v} alt=""></LazyImage>;
                      })}
                    </dt>
                    <dd>
                      <p>
                        <span>{v.source}</span>
                        <span>
                          {getTimeFormatText(new Date(v.releaseTime))}
                        </span>
                      </p>
                    </dd>
                  </dl>
                );
              } else {
                return (
                  <dl
                    key={v.id}
                    onClick={() => navigate(`/home/information/${v.id}`)}
                  >
                    3
                  </dl>
                );
              }
            })}
          </div>
        </WDList>
      </div>
      <div style={{ height: 60 }}>
        <MypatientCieclefooter></MypatientCieclefooter>
      </div>
    </div>
  );
};

export default Index;
